;
(function() {
    require(['js/tools/getarea']);
    /*
     * Sock连接
     */
    function _set_user_pay_ach(pay_ach) {
        App.set("$Cache.pay.pay_ach", pay_ach);
    };
    var user_notify = serverNotify("user");

    function _set_pay_ach(pay_ach) {
        pay_ach._auto_go_online_pay = true;
        App.set("$Cache.pay.pay_ach", pay_ach);
    };

    //订单支付成功后的页面回调
    function _pay_success_cb(new_ach_info) {
        _set_pay_ach(new_ach_info);
        Path.jump("/user/main.html");
    };
    user_notify.on("pay_success", _pay_success_cb);

    user_notify.on("ach.state.changed", function(ach_info) {
        if (App.get("$Cache.pay.pay_ach._id") == ach_info.ach_id) {
            App.set("$Cache.pay.pay_ach.info.state", ach_info.state);
        };
    });

    App.set("_is_weixin", _isWX);
    App.set('$Cache.pay.whichpay', 'pay1');
    App.set('$Event.pay.change_addr', function() {
        App.model.toggle('$Cache.pay.is_change_address');
    });
    App.set('$Event.pay.isadd_addr', function() {
        App.model.toggle('$Cache.pay.isadd_addr');
    });
    App.set('$Event.pay.changepay', function(e, vm) {
        $(this).find('.radio').click();
        App.set('$Cache.pay.whichpay', $(this).attr('name'));
    });

    //订单取消
    App.set("$Event.cancel_ach_success", function(vm, result) {
        Path.jump("/main.html");
    });
    Path.on("/__basename__.html", function(_current_location) {
        var queryString = _current_location.query;
        var ach_id = queryString.get("ach_id");
        console.log(ach_id);
        if (!ach_id) {
            alert("error", "无效的订单编号");
        }
        //获取订单信息
        coAjax.get(appConfig.user.ach_by_id + ach_id, function(result) {
            var _ach_result = result.result;
            App.set("$Cache.pay.pay_ach", result.result);
            if ((result.result.info.state == App.get("config.ACH_STATE.未确认")) && _isWX) {
                coAjax.put(appConfig.user.ach_change_pay_method + App.get("$Cache.pay.pay_ach._id"), {
                    pay_method: "weixin_pay"
                }, function(wx_pay_result) {
                    App.set("$Cache.pay.pay_ach", wx_pay_result.result);
                });
            }
            // 获取用户优惠券
            coAjax.get(appConfig.user.ticket_list, function(ticket_result) {
                var no_use = ticket_result.result.filter(function(v) {
                    return (v.state == 1) && (v.bus_id == busInfo._id);
                });
                var can_use = no_use.filter(function(a) {
                    return a.ticket_factory.info.config.full_cash < _ach_result.finally_cash;
                });
                console.log(no_use);
                App.set("$Cache.pay.user_tickets", can_use);
            });
        }, function(errorCode) {
            console.log("errorCode:", errorCode);
            // alert("error", "无效的订单编号");
            myConfirm("订单号无效，是否回到店铺首页", function() {
                Path.jump("/main.html");
            });
        });

        //获取用户地址列表
        coAjax.get(appConfig.user.address_detail, function(result) {
            App.set("user.address_detail", result.result);
            App.getModel().touchOff("$Cache.pay.pay_ach.info.user_address")
        });

    });
    // 更改为在线支付
    App.set("$Event.pay.change_pay_main_to_online", function() {
        App.set("$Cache.pay.is_pay_offline", false);
        var pay_method;
        if (_isWX) {
            pay_method = "weixin_pay";
            App.set("$Cache.pay.pay_ach.info.pay_method", "weixin_pay");
        } else {
            pay_method = "alipay.wap.auth.authAndExecute";
            App.set("$Cache.pay.pay_ach.info.pay_method", "alipay.wap.auth.authAndExecute");
        };
        change_pay_method(pay_method);
    });
    // 更改为离线支付
    App.set("$Event.pay.change_pay_main_to_offline", function() {
        if (App.get("$Cache.pay.pay_ach.info.is_only_online_pay")) {
            alert("warn", "此商家只支持在线支付！");
            return;
        };
        App.set("$Cache.pay.is_pay_offline", true);
        var pay_method = "payment_in_cash";
        App.set("$Cache.pay.pay_ach.info.pay_method", "payment_in_cash");
        change_pay_method(pay_method);
    });
    // 改变支付方式
    App.set("$Event.pay.change_pay_method", function(e) {
        var pay_method = this.getAttribute("value");
        change_pay_method(pay_method);
    });

    function change_pay_method(pay_method) {
        coAjax.put(appConfig.user.ach_change_pay_method + App.get("$Cache.pay.pay_ach._id"), {
            pay_method: pay_method
        }, function(result) {
            App.set("$Cache.pay.pay_ach", result.result);
            alert("success", "支付方式修改成功");
        }, function(errorCode) {
            alert("error", "支付方式修改失败");
        });
    };
    // 添加地址
    App.set("$Event.pay.add_user_address", function() {
        var new_user_address = {
            province: $("[name='province']").val(),
            town: $("[name='city']").val(),
            county: $("[name='area']").val(),
            // street:
            detail: $("[name='detailed_addre']").val(),
            mobilenumber: $("[name='mobile_num']").val(),
            name: $("[name='name']").val()
        };
        console.log(new_user_address);
        coAjax.post(appConfig.user.add_address, new_user_address, function(result) {
            var address_detail = App.get("user.address_detail");
            address_detail.unshift(result.result);
            App.set("user.address_detail", address_detail);
            App.getModel().touchOff("$Cache.pay.pay_ach.info.user_address");
            App.model.toggle('$Cache.pay.isadd_addr');
            coAjax.put(appConfig.user.ach_change_user_address + App.get("$Cache.pay.pay_ach._id"), {
                user_address_id: result.result._id
            }, function(result) {
                alert('success', "收货地址修改成功");
                App.set("$Cache.pay.pay_ach.info.user_address", result.result);
            }, function(errorCode, xhr, errorMsg) {
                App.getModel().touchOff("$Cache.pay.pay_ach.info.user_address._id")
                alert("error", errorMsg);
            });
            //设置为默认地址
            coAjax.put(appConfig.user.set_default_address, {
                address_id: result.result._id
            }, function(result) {
                App.set("user.default_ua_id", result.result);
                console.log("默认地址修改成功");
            });
        }, function(errorCode, xhr, errorMsg) {
            alert("error", errorMsg);
        });
    });
    //改变订单使用的收货地址
    App.set("$Event.pay.change_user_address", function(e, vm) {
        debugger
        coAjax.put(appConfig.user.ach_change_user_address + App.get("$Cache.pay.pay_ach._id"), {
            user_address_id: vm.get("_id")
        }, function(result) {
            App.model.toggle('$Cache.pay.is_change_address');
            App.set("$Cache.pay.pay_ach.info.user_address", result.result);
        });
    });
    //使用支付宝下单
    App.set("$Event.pays.alipay_build", function() {
        require("coAjax").post(appConfig.server_url + "alipay/create_direct_pay_by_user", {
            WIDout_trade_no: App.get("$Cache.pay.pay_ach._id"),
            WIDsubject: "来自“" + busInfo._id + "”的订单",
            WIDtotal_fee: App.get("$Cache.pay.pay_ach.cash"),
            WIDbody: "",
            WIDshow_url: window.location.toString(),
        }, function(result) {
            // result.result.appendTo(document.body);
            App.set("$Cache.alipay_submit_pay_ach", result.toString);
        }, function(ec, xhr, em) {
            console.log(em)
        });
    });

    // 选择优惠券
    App.set("$Event.pay.choose_ticket", function(e, vm) {
        if (App.get("$Cache.pay_ach.ticket_id") == vm.get("_id")) {
            App.set("$Cache.pay_ach.ticket_id", "");
        } else {
            App.set("$Cache.pay_ach.ticket_id", vm.get("_id"));
        };
    });

    // 使用并绑定优惠券
    App.set("$Event.pay.using_checked_ticket", function() {
        if (!App.get("$Cache.pay_ach.ticket_id")) {
            myConfirm("请先点击要使用的优惠券，再次点击优惠券可取消使用。");
            return;
        };
        myConfirm("确定使用该优惠券吗？", function() {
            coAjax.put(appConfig.user.ach_bind_ticket, {
                ach_id: App.get("$Cache.pay.pay_ach._id"),
                ticket_id: App.get("$Cache.pay_ach.ticket_id")
            }, function(result) {
                alert("优惠码绑定成功");
                console.log(result.result);
                _set_user_pay_ach(result.result);
            });
        });
    });
}());
